package com.sky.service.impl;

import com.sky.constant.AddressBookConstant;
import com.sky.context.BaseContext;
import com.sky.dto.AddressBookAddDOT;
import com.sky.dto.AddressBookSetDefaultDTO;
import com.sky.dto.AddressBookUpdateDOT;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    AddressBookMapper addressBookMapper;

    /**
     * 查询地址
     */
    @Override
    public List<AddressBook> list() {
        Long UserId = BaseContext.getCurrentId();
        return addressBookMapper.selectByUserId(UserId);

    }

    /**
     * 新增地址
     *
     * @param dot
     */

    @Override
    public void add(AddressBookAddDOT dot) {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(AddressBookConstant.NO);
        BeanUtils.copyProperties(dot, addressBook);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据id回显
     *
     * @param id
     * @return
     */

    @Override
    public AddressBook selectById(String id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return addressBook;
    }

    /**
     * 修改
     *
     * @param dto
     */
    @Override
    public void update(AddressBookUpdateDOT dto) {
        Integer isDefault = dto.getIsDefault();
        // 如果是把当前记录修改成默认
        if (isDefault != null && Objects.equals(isDefault, AddressBookConstant.YES)) {
            // 把之前的默认给取消掉
            addressBookMapper.updateUserId(BaseContext.getCurrentId());
            // 设置当前的为默认
            AddressBook addressBook = new AddressBook();
            BeanUtils.copyProperties(dto, addressBook);
            addressBook.setUserId(BaseContext.getCurrentId());
            addressBookMapper.update(addressBook);
        } else {
            // 根据id更新
            AddressBook addressBook = new AddressBook();
            BeanUtils.copyProperties(dto, addressBook);
            addressBook.setUserId(BaseContext.getCurrentId());
            addressBookMapper.update(addressBook);
        }

    }
    /**
     * 默认地址修改
     */
    @Override
    public void setDefault(AddressBookSetDefaultDTO dto) {
        addressBookMapper.updateUserId(BaseContext.getCurrentId());
        // 设置当前的为默认
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(dto.getId());
        addressBook.setIsDefault(AddressBookConstant.YES);
        addressBookMapper.update(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteByid(id);
    }
}